#!/usr/bin/env python3
"""
系统启动脚本
提供多种启动模式和配置选项
"""

import argparse
import sys
import os
import signal
import asyncio
from pathlib import Path

# 添加项目根目录到Python路径
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))

from src.app import create_app
from src.config import config
from src.logger import logger


def setup_signal_handlers():
    """设置信号处理器"""
    def signal_handler(signum, frame):
        logger.info(f"Received signal {signum}, shutting down gracefully...")
        sys.exit(0)
    
    signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGTERM, signal_handler)


def validate_environment():
    """验证运行环境"""
    try:
        # 检查Python版本
        if sys.version_info < (3, 8):
            logger.error("Python 3.8 or higher is required")
            return False
        
        # 检查必要的目录
        required_dirs = ["data", "logs"]
        for dir_name in required_dirs:
            dir_path = project_root / dir_name
            if not dir_path.exists():
                logger.info(f"Creating directory: {dir_path}")
                dir_path.mkdir(parents=True, exist_ok=True)
        
        # 检查配置文件
        config_file = project_root / "config" / "default.yaml"
        if not config_file.exists():
            logger.error(f"Configuration file not found: {config_file}")
            return False
        
        return True
        
    except Exception as e:
        logger.error(f"Environment validation failed: {e}")
        return False


def run_development():
    """开发模式运行"""
    import uvicorn

    logger.info("Starting in development mode...")

    # 开发模式配置 - 使用import string以支持reload
    uvicorn.run(
        "src.app:create_app",
        factory=True,
        host="0.0.0.0",
        port=7880,
        reload=True,
        reload_dirs=[str(project_root / "src")],
        log_level="debug"
    )


def run_production():
    """生产模式运行"""
    import uvicorn
    
    logger.info("Starting in production mode...")
    
    app = create_app()
    
    # 生产模式配置
    server_config = config.get('server', {})
    
    uvicorn.run(
        app,
        host=server_config.get('host', '0.0.0.0'),
        port=server_config.get('port', 7880),
        workers=server_config.get('workers', 1),
        log_level=server_config.get('log_level', 'info'),
        access_log=server_config.get('access_log', True)
    )


def run_worker():
    """后台工作进程模式"""
    logger.info("Starting in worker mode...")
    
    async def worker_main():
        from src.services.subscription_service import subscription_service
        from src.services.discovery_service import discovery_service
        from src.services.notification_service import notification_service
        from src.services.event_dispatcher import event_dispatcher
        
        try:
            # 启动所有服务
            await event_dispatcher.start()
            await notification_service.start()
            await subscription_service.start()
            await discovery_service.start()
            
            logger.info("All worker services started successfully")
            
            # 保持运行
            while True:
                await asyncio.sleep(60)
                logger.debug("Worker heartbeat")
                
        except KeyboardInterrupt:
            logger.info("Worker shutdown requested")
        except Exception as e:
            logger.error(f"Worker error: {e}")
        finally:
            # 停止所有服务
            await discovery_service.stop()
            await subscription_service.stop()
            await notification_service.stop()
            await event_dispatcher.stop()
            logger.info("All worker services stopped")
    
    asyncio.run(worker_main())


def run_test():
    """测试模式运行"""
    logger.info("Starting in test mode...")
    
    async def test_main():
        from src.storage import data_manager
        from src.services.event_dispatcher import event_dispatcher, EventType
        
        try:
            # 启动事件分发器
            await event_dispatcher.start()
            
            # 运行一些测试
            logger.info("Running system tests...")
            
            # 测试数据存储
            models = await data_manager.get_models()
            logger.info(f"Found {len(models)} models in storage")
            
            # 测试事件系统
            await event_dispatcher.emit(
                EventType.SYSTEM_STATUS,
                {"test": True, "message": "Test event"},
                "test_runner"
            )
            
            logger.info("System tests completed successfully")
            
        except Exception as e:
            logger.error(f"Test failed: {e}")
        finally:
            await event_dispatcher.stop()
    
    asyncio.run(test_main())


def show_status():
    """显示系统状态"""
    logger.info("Checking system status...")
    
    # 检查配置
    print(f"Configuration loaded: {bool(config)}")
    print(f"API version: {config.get('api', {}).get('version', 'unknown')}")
    
    # 检查数据目录
    data_dir = project_root / "data"
    if data_dir.exists():
        files = list(data_dir.glob("*.json"))
        print(f"Data files: {len(files)}")
    else:
        print("Data directory not found")
    
    # 检查日志目录
    logs_dir = project_root / "logs"
    if logs_dir.exists():
        log_files = list(logs_dir.glob("*.log"))
        print(f"Log files: {len(log_files)}")
    else:
        print("Logs directory not found")


def main():
    """主函数"""
    parser = argparse.ArgumentParser(description="Model Subscription System")
    parser.add_argument(
        "mode",
        choices=["dev", "prod", "worker", "test", "status"],
        help="运行模式"
    )
    parser.add_argument(
        "--config",
        help="配置文件路径",
        default="config/default.yaml"
    )
    parser.add_argument(
        "--log-level",
        choices=["DEBUG", "INFO", "WARNING", "ERROR"],
        default="INFO",
        help="日志级别"
    )
    
    args = parser.parse_args()
    
    # 设置信号处理器
    setup_signal_handlers()
    
    # 验证环境
    if not validate_environment():
        sys.exit(1)
    
    # 根据模式运行
    try:
        if args.mode == "dev":
            run_development()
        elif args.mode == "prod":
            run_production()
        elif args.mode == "worker":
            run_worker()
        elif args.mode == "test":
            run_test()
        elif args.mode == "status":
            show_status()
        else:
            logger.error(f"Unknown mode: {args.mode}")
            sys.exit(1)
            
    except KeyboardInterrupt:
        logger.info("Shutdown requested by user")
    except Exception as e:
        logger.error(f"Startup failed: {e}")
        sys.exit(1)


if __name__ == "__main__":
    main()
